import React from 'react';
import PropTypes from 'prop-types';
import {Card, Button, Row, Col, Form, Spin, Table, Popconfirm} from 'antd';
import TextInput from 'Shared/components/TextInput';
import routes from './routes';
import {newOrUpdateValidator} from './validator';
import {conventEnumValueToString} from '../utils';
import Return from '../common/Return';
import BankSelectPanel from './BankSelectPanel';
import FileUpload from './FileUpload';
import {currency, recommendLevel} from '../Enum';
import {FORM_OPTIONS, FORM_ROW_OPTIONS, TABLE, FIXED_COLUMN_WIDTH} from '../constants';
import {getDetail} from './api';
const EMPTY_ARRAY = [];
const FormItem = Form.Item;
export class NewPanel extends React.PureComponent {
    state = {
        isValidate: false,
        hasOperat: false,
        loading: false,
        showBankSelectPanel: false,
        data: {},
        details: [],
    }
   
    componentDidMount() {
        if(this.props.id)
            this.getDetailInfo();
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    getDetailInfo = () => {
        const id = this.props.id;
        this.setState({loading: true});
        getDetail(id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        loading: false,
                        data: res.data,
                        details: res.data.details,
                    });
                else
                    this.setState(({
                        loading: false
                    }));
            });
    }
    removeLogoFilePath = file => {
        const data = this.state.data;
        const index = data.logoAttachments.findIndex(item => item.fileId === file.fileId);
        if(index === -1)
            return null;
        const logoAttachments = data.logoAttachments || [];
        logoAttachments.splice(index, 1);
        this.setState({
            data: {
                ...data,
                logoAttachments
            },
            hasOperat: true,
        });
    }
    removeSignatureFilePath = file => {
        const data = this.state.data;
        const index = data.signatureAttachments.findIndex(item => item.fileId === file.fileId);
        if(index === -1)
            return null;
        const signatureAttachments = data.signatureAttachments || [];
        signatureAttachments.splice(index, 1);
        this.setState({
            data: {
                ...data,
                signatureAttachments
            },
            hasOperat: true,
        });
    }
    onChangeLogoUpload = value => {
        const data = this.state.data;
        const logoAttachments = data.logoAttachments || [];
        logoAttachments.push(value[0]);
        this.setState({
            data: {
                ...data,
                logoAttachments
            },
            hasOperat: true,
        });
    }
    onChangeSignatureUpload = value => {
        const data = this.state.data;
        const signatureAttachments = data.signatureAttachments || [];
        signatureAttachments.push(value[0]);
        this.setState({
            data: {
                ...data,
                signatureAttachments
            },
            hasOperat: true,
        });
    }
    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onSubmit = () => {
        this.setState({
            loading: true
        });
        const data = this.state.data;
        const details = this.state.details;
        const isValid = newOrUpdateValidator(data);
        if(!isValid) {
            this.setState({
                isValidate: true,
                loading: false
            });
            return;
        }
        this.props.onSubmit(data, details)
            .then(res => {
                if(res.success)
                    this.props.successReturn();
                if(!this.isunmount)
                    this.setState({loading: false});
            });
    }
    onClickReturnBtn = () => {
        this.props.onCancel();
    }
    onClickAddDetailBtn = () => {
        this.setState({
            showBankSelectPanel: !this.state.showBankSelectPanel
        });
    }
    onSelectBank = value => {
        const details = this.state.details;
        value.map(p => {
            const detail = this.state.details.find(d => d.id === p.id);
            if(!detail) {
                const detail = {
                    id: p.id,
                    code: p.code,
                    name: p.name,
                    engName: p.engName,
                    accountCode: p.accountCode,
                    account: p.account,
                    currency: p.currency,
                    recommendLevel: p.recommendLevel,
                };
                details.push(detail);
            }
            return p;
        });
        this.setState({
            showBankSelectPanel: false,
            hasOperat: true,
            details
        });
    }
    onDeleteAll = () => {
        this.setState({
            details: [],
            hasOperat: true
        });
    }
    onDeleteDetail = e => {
        const id = e.target.dataset.id;
        const details = this.state.details.filter(p => p.id !== id);
        this.setState({
            details,
            hasOperat: true
        });
    }
    render() {
        const {data, details, isValidate} = this.state;
        const {formatMessage} = this.props.intl;
        const columns = [{
            title: formatMessage({
                id: 'addPanel.column.code',
                defaultMessage: '银行编号'
            }),
            dataIndex: 'code',
        }, {
            title: formatMessage({
                id: 'addPanel.column.name',
                defaultMessage: '银行名称'
            }),
            dataIndex: 'name',
        }, {
            title: formatMessage({
                id: 'addPanel.column.account',
                defaultMessage: '银行账号'
            }),
            dataIndex: 'account',
        }, {
            title: formatMessage({
                id: 'addPanel.column.currency',
                defaultMessage: '币种'
            }),
            dataIndex: 'currency',
            render: text => conventEnumValueToString(currency, text)
        }, {
            title: formatMessage({
                id: 'addPanel.column.recommendLevel',
                defaultMessage: '推荐程度'
            }),
            dataIndex: 'recommendLevel',
            render: text => conventEnumValueToString(recommendLevel, text)
        }, {
            title: formatMessage({
                id: 'addPanel.column.accountCode',
                defaultMessage: '银行识别码'
            }),
            dataIndex: 'accountCode',
        }, {
            title: formatMessage({
                id: 'addPanel.column.engName',
                defaultMessage: '银行英文名称'
            }),
            dataIndex: 'engName',
        }, {
            title: details.length > 0
                ? (
                    <Popconfirm placement="topRight" title={formatMessage({
                        id: 'addPanel.validation.isDelete',
                        defaultMessage: '是否确认全部删除？'
                    })} onConfirm={this.onDeleteAll} >
                        <a>{formatMessage({
                            id: 'addPanel.validation.clear',
                            defaultMessage: '清空'
                        })}</a>
                    </Popconfirm>
                )
                : null,
            dataIndex: 'id',
            fixed: 'right',
            width: FIXED_COLUMN_WIDTH,
            render: text => <a data-id={text} onClick={this.onDeleteDetail}>{formatMessage({
                id: 'addPanel.validation.delete',
                defaultMessage: '删除'
            })}</a>
        }];
        return (
            <div>
                <Spin spinning={this.state.loading}>
                    <Form className="form-standard">
                        <Card title={formatMessage({
                            id: 'addPanel.card.title',
                            defaultMessage: '基本信息'
                        })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.data.code',
                                        defaultMessage: '编号'
                                    })}{...FORM_OPTIONS.item} validateStatus={isValidate && !data.code ? 'error' : null} required >
                                        {data.id ? data.code : <TextInput
                                            name="code"
                                            value={data.code}
                                            onBlur={this.onChange}/>}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.data.name',
                                        defaultMessage: '名称'
                                    })}{...FORM_OPTIONS.item} validateStatus={isValidate && !data.name ? 'error' : null} required ><TextInput
                                            name="name"
                                            value={data.name}
                                            onBlur={this.onChange}/></FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.data.englishName',
                                        defaultMessage: '公司英文名称'
                                    })}{...FORM_OPTIONS.item} validateStatus={isValidate && !data.englishName ? 'error' : null} required ><TextInput
                                            name="englishName"
                                            value={data.englishName}
                                            onBlur={this.onChange}/></FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.data.address',
                                        defaultMessage: '地址'
                                    })}{...FORM_OPTIONS.item} validateStatus={isValidate && !data.address ? 'error' : null} required ><TextInput
                                            name="address"
                                            value={data.address}
                                            onBlur={this.onChange}/></FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.data.contactNumber',
                                        defaultMessage: '电话'
                                    })}{...FORM_OPTIONS.item} validateStatus={isValidate && !data.contactNumber ? 'error' : null} required ><TextInput
                                            name="contactNumber"
                                            value={data.contactNumber}
                                            onBlur={this.onChange}/></FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.data.fax',
                                        defaultMessage: '传真'
                                    })}{...FORM_OPTIONS.item} validateStatus={isValidate && !data.fax ? 'error' : null} required ><TextInput
                                            name="fax"
                                            value={data.fax}
                                            onBlur={this.onChange}/></FormItem>
                                </Col>
                            </Row>
                            <Row className="row-margin">
                                <Col>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.data.remark',
                                        defaultMessage: '备注'
                                    })}{...FORM_ROW_OPTIONS.item}><TextInput
                                            name="remark"
                                            type="textarea"
                                            value={data.remark}
                                            onBlur={this.onChange}/></FormItem>
                                </Col>
                            </Row>
                        </Card>
                        <Card
                            title={formatMessage({
                                id: 'addPanel.operation.detail',
                                defaultMessage: '银行清单'
                            })} extra={<div>
                                <Button
                                    size="small"
                                    onClick={this.onClickAddDetailBtn}>
                                    {formatMessage({
                                        id: 'addPanel.btn.add',
                                        defaultMessage: '增加清单'
                                    })}
                                </Button>
                            </div>}>
                            <Table
                                className="white-space-nowrap"
                                columns={columns}
                                rowKey="id"
                                pagination={false}
                                dataSource={details}
                                {...TABLE} />
                        </Card>
                        <Card title={formatMessage({
                            id: 'reportPanel.title.logoFiles',
                            defaultMessage: 'logo附件'
                        })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FileUpload onChange={this.onChangeLogoUpload}
                                        onRemove={this.removeLogoFilePath}
                                        fileList={data.logoAttachments || EMPTY_ARRAY}/>
                                </Col>
                            </Row>
                        </Card>
                        <Card title={formatMessage({
                            id: 'reportPanel.title.signatureFiles',
                            defaultMessage: '签章附件'
                        })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FileUpload onChange={this.onChangeSignatureUpload}
                                        onRemove={this.removeSignatureFilePath}
                                        fileList={data.signatureAttachments || EMPTY_ARRAY}/>
                                </Col>
                            </Row>
                        </Card>
                    </Form>
                    <Card>
                        <Row>
                            <Col className="col-align-right">
                                <Button key="audit"
                                    onClick={this.onSubmit}
                                    type="primary"
                                    loading={this.state.loading}>
                                    {formatMessage({
                                        id: 'addPanel.btn.submit',
                                        defaultMessage: '保存'
                                    })}</Button>
                            </Col>
                        </Row>
                    </Card>
                </Spin>
                {
                    this.state.showBankSelectPanel && <BankSelectPanel
                        selectKey={details.id}
                        onCancel={this.onClickAddDetailBtn}
                        onSelect={this.onSelectBank} />
                }
                <div className="page-toolbar">
                    <Return
                        onConfirm={this.onClickReturnBtn}
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

NewPanel.propTypes = {
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    intl: PropTypes.object,
};

import {connect} from 'react-redux';
import {injectIntl} from './intl';
import {tableSearch, onSubmit} from './actions';

const mapDispatchToProps = (dispatch, props) => ({
    onSubmit: (data, details) => dispatch(onSubmit(data, details)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(null, mapDispatchToProps)(injectIntl(NewPanel));
